<template>
  <div>

    <el-dialog
      id="dialogBox"
      title="轮播图配置"
      width="70%"
      :visible.sync="visible"
      top="2vh"
      class="boxMargin"
    >
      <div class="boxMargin">

        <el-row :gutter="20" class="boxMargin">

          <el-col :span="3" class="inputName"><em>*</em> 标题：</el-col>
          <el-col :span="8">
            <el-input
              v-model.trim="dialogData.slideshowTitle"
              placeholder="请输入标题"
            />
          </el-col>

        </el-row>
        <el-row :gutter="20" class="boxMargin">
          <el-col :span="3" class="inputName"><em>*</em>排序：</el-col>
          <el-col :span="8">
            <el-input v-model="dialogData.slideshowSort" type="number" placeholder="请输入" />
          </el-col>
        </el-row>
        <el-row :gutter="20" class="boxMargin">
          <el-col :span="3" class="inputName"><em>*</em>上传图片：</el-col>
          <el-col :span="16">
            <div class="upLoadImg">
              <el-upload
                ref="materialMap"
                class="avatar-uploaders"
                action
                :show-file-list="false"

                :multiple="true"
                :auto-upload="false"
                :on-change="beforeMaterialUploadType"
                accept=".png,.jpg"
              >
                <div class="img-show">
                  <img v-if="dialogData.slideshowFile" :src="dialogData.slideshowFile" class="avatar">
                  <i v-else class="el-icon-plus" />
                </div>
              </el-upload>
              <div class="rule">
                <p>尺寸：940*400px</p>
                <p>格式：jpg/png</p>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="boxMargin">
          <el-col :span="3" class="inputName">是否发布：</el-col>
          <el-col :span="8">
            <template>
              <el-switch
                v-model="dialogData.status"
                :active-value="2"
                :inactive-value="1"
              />
            </template>

          </el-col>
        </el-row>
        <el-row :gutter="20" class="boxMargin">
          <el-col :span="3" class="inputName"><em>*</em>跳转：</el-col>
          <el-col :span="15">
            <div class="flotright">
              <el-radio-group v-model="dialogData.slideshowType">
                <div class="marginhetght">
                  <el-radio :label="0">不跳转</el-radio>
                </div>
                <div class="marginhetght">
                  <el-radio :label="2">链接URL
                    <el-input v-model="dialogData.content" placeholder="请输入" />
                  </el-radio>
                </div>
                <div class="marginhetght">
                  <el-radio :label="1">商品
                    <el-autocomplete
                      v-model="itemName"
                      :fetch-suggestions="querySearchAsync"
                      placeholder="请输入内容"
                      @select="handleSelect"
                    />
                  </el-radio>
                </div>

              </el-radio-group>

            </div>

          </el-col>
        </el-row>
        <el-row :gutter="20" class="">
          <el-col :span="24" style="text-align: center;">
            <div class="contion-header text-r">
              <el-button type="primary" @click.native="onAddCourseFn">完成</el-button>
              <el-button type="primary" @click.native="caloseDialogFn">取消</el-button>
            </div>
          </el-col>
        </el-row>

      </div>

    </el-dialog>
  </div>
</template>
<script>

import _validate from '@/framework/commonJs/wptx_validate'
import _tools from '@/framework/commonJs/wptx_tools'
import { global } from '@/filter/global-api'
import { _storeitemList } from '@/framework/API/carouse'
import _api from '@/framework/API/carouse'

export default {
  components: {

  },
  data() {
    return {
      visible: false,
      dialogData: {
        slideshowTitle: '',
        slideshowSort: '',

        status: 2,

        slideshowType: 0, // 跳转  0 1=商品 2

        productId: '',

        slideshowFile: '',
        content: ''

      },
      itemName: '', // 商品
      id: '', // 编辑id
      pageData: {
        pageNo: 1,
        pageSize: 10000,
        total: 1,
        pageSizes: [10, 20, 50, 100]
      }
    }
  },
  mounted() {

  },
  methods: {
    initFn(id) {
      this.clearFn()
      this.id = id
      if (this.id) {
        this.initEditFn(this.id)
      }
      this.visible = true
    },
    clearFn() {
      this.dialogData.slideshowTitle = ''
      this.dialogData.slideshowSort = ''
      this.dialogData.status = 2
      this.itemName = ''
      this.dialogData.slideshowType = 0
      this.dialogData.productId = ''
      this.dialogData.content = ''
      this.dialogData.slideshowFile = ''
    },
    initEditFn(id) {
      const self = this
      const params = {
        id: id
      }
      _api.getSlideshowById(self, params, self.callBack_DetailtPage)
    },
    callBack_DetailtPage(data) {
      this.dialogData = data
      this.dialogData.status = Number(data.status)
      if (data.slideshowType == 0) {
        this.dialogData.slideshowType = 0
        this.dialogData.content = ''
      }
      if (data.slideshowType == 1) {
        this.dialogData.slideshowType = 1
        console.log(data.content.split(','))
        this.itemName = data.content.split(',')[1]
        this.dialogData.productId = data.content.split(',')[0]
        this.dialogData.content = ''
      }
      if (data.slideshowType == 2) {
        this.dialogData.slideshowType = 2
        this.dialogData.content = data.content
      }
    },

    beforeMaterialUploadType(file) {
      const self = this

      self.fileCheck(file)
    },
    // 验证图片大小以及格式
    fileCheck(file, value, imageSort) {
      const self = this
      const extName = file.name
        .substring(file.name.lastIndexOf('.'))
        .toLowerCase()
      const AllUpExt = '.png|.jpg|'

      if (AllUpExt.indexOf(extName + '|') == '-1') {
        _validate.openTip(self, '上传文件格式错误', 'warning')
        return false
      }
      self.proportion(file, value).then(function(data) {
        if (data) {
          self.itemUpload(file)
        }
      })
    },
    // 上传
    itemUpload(file) {
      const self = this
      const fd = new FormData()
      fd.append('file', file.raw)

      const url = process.env.VUE_APP_IMAGE_UPLOAD_PRODUCT
      global.postupload(
        url,
        null,
        fd,
        function(response) {
          const res = JSON.parse(response)

          if (res.code != 200) {
            _validate.openTip(self, res.message, 'error')
          } else {
            _validate.openTip(self, '图片上传成功', 'success')
            self.dialogData.slideshowFile = res.data.fileUrl
          }
        },
        function(error) {
          self.$message.error(error)
        }
      )
    },
    // 验证图片比例和图片尺寸
    proportion(file, value) {
      const self = this
      const p = new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file.raw) // 必须用file.raw
        reader.onload = () => {
        // 让页面中的img标签的src指向读取的路径
          const img = new Image()
          img.src = reader.result

          img.onload = () => {
            if (img.width != 940 && img.height != 400) {
              self.$message.warning(
                `图片的尺寸为940*400px，当前文件${img.width}×${img.height}，请您重新选择`
              )
              resolve(false)
            } else {
              resolve(true)
            }
          }
        }
      })
      return p
    },
    caloseDialogFn() {
      this.visible = false
    },

    // 保存轮播图
    onAddCourseFn() {
      const self = this

      if (self.dialogData.slideshowTitle == '') {
        _validate.openTip(self, '请输入标题', 'warning')
        return false
      }
      if (self.dialogData.slideshowSort == '') {
        _validate.openTip(self, '请输入排序', 'warning')
        return false
      }
      if (self.dialogData.slideshowFile == '') {
        _validate.openTip(self, '请上传图片', 'warning')
        return false
      }
      if (self.dialogData.slideshowType == 2 && self.dialogData.content == '') {
        _validate.openTip(self, '请输入跳转链接', 'warning')
        return false
      }
      if (self.dialogData.slideshowType == 1 && self.itemName == '') {
        self.dialogData.content = ''
        _validate.openTip(self, '请输入商品名称', 'warning')
        return false
      }
      const {
        slideshowTitle,
        slideshowSort,
        slideshowFile,
        status,
        slideshowType

      } = self.dialogData
      const params = {
        slideshowTitle: slideshowTitle,
        slideshowSort: slideshowSort,
        slideshowFile: slideshowFile,
        status: status,
        slideshowType: slideshowType,
        content: ''
      }
      if (self.dialogData.slideshowType == 1) {
        params.content = self.dialogData.productId + ',' + self.itemName
      }
      if (self.dialogData.slideshowType == 2) {
        params.content = self.dialogData.content
      }

      if (self.id) {
        params.id = self.id
        _api.slideshowUpdate(self, params, self.callBack_CareatPage)
      } else {
        _api.slideshowCreate(self, params, self.callBack_CareatPage)
      }
    },
    callBack_CareatPage(data) {
      this.caloseDialogFn()
      this.$parent.seachListFn()
    },

    // 商品搜索
    async querySearchAsync(queryString, cb) {
      const self = this
      const params = {
        itemName: self.itemName
      }
      const { result } = await _storeitemList(params)
      var list = [{}]

      for (const i of result.result) {
        i.value = i.itemName // 将想要展示的数据作为value
      }
      list = result.result
      cb(list)
    },

    handleSelect(item) {
      console.log(item)
      this.dialogData.productId = item.id
    }
  }

}

</script>
<style scoped lang="scss">
.upLoadImg{
    width: 100%;
    display: flex;
    align-items: center;
    .avatar-uploaders {
    width: 150px;
    height: 80px;
    border: 1px dashed #d9d9d9;
    text-align: center;
    line-height: 80px;
    .img-show{
      width: 150px;
      height: 80px;
      line-height: 80px;
      img{
        width: 100%;
        height: 100%;
      }
    }
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
    .rule{
      line-height: 10px;
      margin-left: 20px;
    }
}
  .flotright{

    margin: 16px 0;
    .marginhetght{
      margin-bottom: 20px;
    }
  }
  .boxMargin{
    em{
      color: #ff4949;
       margin-right: 4px;
    }
  .el-row {
      line-height: 36px;
  }
  }
</style>
